package com.woniuxy.usercoachassemble.controller;


import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.woniuxy.usercoachassemble.entity.Adress;
import com.woniuxy.usercoachassemble.entity.User;
import com.woniuxy.usercoachassemble.entity.Userinfo;
import com.woniuxy.usercoachassemble.service.AdressService;
import com.woniuxy.usercoachassemble.service.UserService;
import com.woniuxy.usercoachassemble.service.UserinfoService;
import com.woniuxy.usercoachassemble.service.impl.UserinfoServiceImpl;
import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import org.example.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2020-07-13
 */
@RestController
@RequestMapping("adress")
public class AdressController {
@Autowired
    private AdressService adressServiceImpl;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserinfoService userinfoServiceImpl;
    @Autowired
    private UserService userServiceImpl;
//新增学员位置
@RequestMapping("/addadressbyuserid")
    public  void  addadressbyuserid(Adress address, HttpServletRequest request){
//存入redis
    Long addedNum = redisTemplate.opsForGeo()
            .add("address",new Point(address.getLongtitude(),address.getLatitude()), request.getHeader("userId"));
    System.out.println(addedNum);
}
//修改位置
        @RequestMapping("updateadressbyusrid")
    public  Result updateadressbyusrid(Adress address, HttpServletRequest request){
            String userId=request.getHeader("userId");
            System.out.println(userId);
        Long deletedNum = redisTemplate.opsForGeo().remove("address",userId+"");
        Long addedNum = redisTemplate.opsForGeo()
                .add("address",new Point(address.getLongtitude(),address.getLatitude()),userId+"");
//        同步更新到数据库
            adressServiceImpl.update().eq("user_Id",userId)
                    .set("longtitude",address.getLongtitude())
                    .set("latitude",address.getLatitude()).update();
        return Result.Success();
    }
//获取自己当前的位置
    @RequestMapping("selectadressbuyuserid")
    public Result selectadressbuyuserid(HttpServletRequest request){
       int userId= Integer.parseInt(request.getHeader("userId"));
        System.out.println(userId);
        List<Point> points = redisTemplate.opsForGeo().position("address",userId+"");
        List<Adress> lis=new ArrayList<>();
        for(Point point:points){
            Adress address=new Adress();

            address.setUserId(userId);
            address.setLongtitude(point.getX());
            address.setLatitude(point.getY());
            lis.add(address);
        }
        return  Result.Success( lis);
   }

// 获取周围的人/传入的是公里数 和当前用户的id
 @RequestMapping("selectpersonaroundwithyou")
 public List<Map<String,Object>> testNearByPlace(HttpServletRequest request, double length){
    int userId=request.getIntHeader("userId");
     Distance distance = new Distance(length,Metrics.KILOMETERS);
     RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands
             .GeoRadiusCommandArgs
             .newGeoRadiusArgs()
             .includeDistance()
             .includeCoordinates()
             .sortAscending();
     GeoResults<RedisGeoCommands.GeoLocation<String>>  results = redisTemplate.opsForGeo()
             .radius("address",userId+"",distance,args);
     List<Map<String,Object>> list=new ArrayList<>();
     for (Iterator<GeoResult<RedisGeoCommands.GeoLocation<String>>> it = results.iterator(); it.hasNext(); )
     {
         Map<String,Object> map=new HashMap<>();
         GeoResult<RedisGeoCommands.GeoLocation<String>> result = it.next();
         map.put("userId",result.getContent().getName());
         map.put("point",result.getContent().getPoint());
         map.put("length",result.getDistance());
         //查询昵称
         Userinfo userinfo=userinfoServiceImpl.query().eq("user_id",Integer.parseInt(result.getContent().getName())).one();
          if (userinfo!=null){
              String nickname=userinfo.getNickname();
              map.put("nickname",nickname);
          }
         User user =userServiceImpl.query().eq("user_id",Integer.parseInt(result.getContent().getName())).one();
         if (user!=null){
             int roleid=user.getRoleId();
             if (roleid==1) map.put("roletype","学员");
             if (roleid==2) map.put("roletype","教练");
         }
         list.add(map);
     }

     return list;
 }
//获取周围的人的id
    public List<Integer> getaroundpersonswithyou(HttpServletRequest request, double distance){
        List<Map<String,Object>> list= testNearByPlace(request,distance);

        List<Integer> lis=new ArrayList<>();
        for (Map<String,Object> li:list){
            String id = (String) li.get("userId");
            lis.add(Integer.parseInt(id));
        }
        return lis;
    }

}

